package com.hyq.learn.common.config;

import com.hyq.learn.common.constant.RequestParamConstants;
import com.hyq.learn.security.cipher.CipherAlgorithm;
import com.hyq.learn.security.cipher.CipherDecision;
import com.hyq.learn.security.cipher.CipherFilter;
import com.hyq.learn.security.cipher.CipherKey;
import com.hyq.learn.security.cipher.DESCipherAlgorithm;
import com.hyq.learn.security.cipher.DESCipherDecision;
import com.hyq.learn.security.cipher.KeyProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;

/**
 * @author : heyuqin
 * @since : 2024/03/06 11:55
 */
@Configuration
@ConditionalOnClass(value = {CipherFilter.class})
public class CipherAutoConfiger {
    private static final Logger log = LoggerFactory.getLogger(CipherAutoConfiger.class);

    public static final int ORDER = 10;

    @Bean
    public FilterRegistrationBean<CipherFilter> cipherFilter(
            KeyProvider key, CipherAlgorithm cipherAlgorithm, CipherDecision cipherDecision,
            HandlerExceptionResolver handlerExceptionResolver) {
        log.info("Initializing cipherFilter");
        CipherFilter cipherFilter = new CipherFilter(key, cipherAlgorithm, cipherDecision, "X-Crypto", handlerExceptionResolver);
        FilterRegistrationBean<CipherFilter> registration = new FilterRegistrationBean<>(cipherFilter);
        registration.addUrlPatterns("/api/*");
        registration.setOrder(ORDER);
        registration.setName("cipherFilter");
        return registration;
    }

    @Bean
    public CipherDecision cipherDecision() {
        return new DESCipherDecision();
    }

    @Bean
    public KeyProvider keyProvider() {
        return request -> {
            String apiKey = request.getParameter(RequestParamConstants.API_KEY);
            if (!"hyqzdtql".equals(apiKey)) {
                throw new RuntimeException("api_key 无效");
            }
            // 当前加解密秘钥是api_key所对应的经过base64编码之后的字符串，实际上应该使用另一个字符串去进行加解密，该字符串和当前api_key关联起来（从库里面去查！！！）
            // hyqzdtql的base64加密后的字符串
            String desKey = "aHlxemR0cWw=";
            return new CipherKey(desKey);
        };
    }

    @Bean
    public CipherAlgorithm cipherAlgorithm() {
        return new DESCipherAlgorithm();
    }
}
